package com.cyan.app.workflow.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author tyter
 *
 */
public class FileUtils {

	/**
	 * @param path
	 * @return 
	 * 			if path exist return true, otherwise return false.
	 */
	public static boolean pathIsExist(String path) {
		if (path == null) {
			return false;
		}
		File file = new File(path);
		return file.exists();
	}
	
	/**
	 * @param path
	 * @return
	 * 			if path exist or create path successfully return true, otherwise return false.
	 */
	public static boolean createPath(String path) {
		if (path == null) {
			return false;
		}
		File file = new File(path);
		
		if (file.exists()) {
			return true;
		}
		
		return file.mkdir();
	}
	
	
	/**
	 * @param path
	 * @return
	 * 			if current path's parent folder path exist return parent folder path, otherwise return null.
	 */
	public static String getParentFolderPath(String path){
		if (path == null) {
			return null;
		}
		int index = path.lastIndexOf(File.separatorChar);
		if (index != -1) {
			return path.substring(0, index);
		}
		return null;
	}
	
	/**
	 * @param path
	 * @return
	 * 			If recursively create a path success return true, otherwise return false.
	 */
	public static boolean createPathRecursive(String path) {
		if (path == null) {
			return false;
		}
		StringBuilder tmpPath = new StringBuilder("");
		while (path != null) {
			int index = path.indexOf(File.separatorChar);
			if (index == -1 || index >= path.length() - 1) {
				break;
			}
			tmpPath.append(path.substring(0, index + 1));
			if (!createPath(tmpPath.toString())) {
				return false;
			}
			path = path.substring(index + 1);
		}
		
		if (path.length() > 0) {
			tmpPath.append(path);
			if (!createPath(tmpPath.toString())) {
				return false;
			}
		}
		
		return true;
	}

	public static String getFileContent(String filePath) {
		InputStream in = null;
		try {
			in = new FileInputStream(filePath);
		} catch (Exception e) {
			return "";
		}
		return getFileContent(in);
	}

	public static String getFileContent(InputStream in) {
		StringBuilder result = new StringBuilder("");
		BufferedReader bufReader = null;
		InputStreamReader inputReader = null;
		try {
			inputReader = new InputStreamReader(in, "UTF-8");
			bufReader = new BufferedReader(inputReader);
			String line = "";
			while ((line = bufReader.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
		} finally {
			try {
				if (bufReader != null) {
					bufReader.close();
				}
				if (inputReader != null) {
					inputReader.close();
				}
			} catch (IOException e) {
			}
		}
		return result.toString();
	}
}
